package com.tar.commons.web.utils;

import java.io.File;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.tar.commons.utils.ConfigUtil;
import com.tar.extra.ueditor.PathFormat;

public class UploaderUtil {
	
	static final Logger logger = LoggerFactory.getLogger(UploaderUtil.class) ;

	public static UploaderVo upload(MultipartHttpServletRequest multipartRequest) {
		return upload(multipartRequest, null);
	}
	
	public static UploaderVo upload(MultipartHttpServletRequest multipartRequest, String destDir) {
		String path = multipartRequest.getContextPath();
		String basePath = multipartRequest.getScheme()+"://"+multipartRequest.getServerName()+":"+multipartRequest.getServerPort()+path;
		//上传文件的相对路径
		String destPath = ConfigUtil.get("destDir") + (destDir!=null&&!"".equals(destDir.replaceAll(" ", ""))?destDir:"") ;
		//上传文件的绝对路径
		String absPath = multipartRequest.getSession().getServletContext().getRealPath(destPath) ;
		String fileUrl = PathFormat.format(basePath + destPath) ;
		
		
		UploaderVo vo = new UploaderVo() ;
		
		MultiValueMap<String, MultipartFile> files = multipartRequest.getMultiFileMap() ;
		List<MultipartFile> list = files.get("file") ;
		for (MultipartFile multipartFile : list) {
			long size = multipartFile.getSize() ;
			String contentType = multipartFile.getContentType() ;
			String originName = multipartFile.getOriginalFilename() ;
			String baseName = FilenameUtils.getBaseName(originName) ;
			String extension = FilenameUtils.getExtension(originName) ;
			
			try {
				String fileOutPath = absPath + File.separator + baseName + "." + extension ;
				FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), new File(fileOutPath)) ;
				
				
				vo.setOriginName(originName);
				vo.setContentType(contentType);
				vo.setSize(size);
				vo.setBasePath(basePath);
				vo.setAbsPath(absPath);
				vo.setFileUrl(fileUrl + originName);
				
				logger.debug("文件上传成功，返回数据==》{}",JSON.toJSONString(vo));
				
				return vo ;
			} catch (Exception e) {
				vo.setState(false);
				logger.error("文件上传发生异常：{}", e.getMessage());
			}
			
		}
		return vo ;
	}
	
}
